package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.my.adapter.MyCollectAdapter;
import com.example.lenovo.asia5b.my.bean.MyCollectBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PublicDialog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.lv_message;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * 我的收藏
 * Created by lenovo on 2017/7/21.
 */

public class MyCollectActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener {
    private ListView lv_my_collect;
    private MyCollectAdapter adapter;
    private LoadingDalog loadingDalog;
    private int page = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private List<MyCollectBean> lists = null;
    //删除收藏
    private MyCollectBean delBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        initView();
        myCollectData();
    }

    public void initView() {
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.my_collect));
        F.id(R.id.public_img_righe).visibility(View.VISIBLE);
        F.id(R.id.public_img_righe).clicked(this);
        pullToRefreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(public_btn_left).clicked(this);
        lv_my_collect = (ListView) findViewById(lv_message);
        adapter = new MyCollectAdapter(this);
        lv_my_collect.setAdapter(adapter);
        lv_my_collect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(MyCollectActivity.this, CommodityDetActivity.class);
                intent.putExtra("goods_id", adapter.getLists().get(i).goods_id);
                startActivityForResult(intent,0);
            }
        });
        lv_my_collect.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            myCollectData();
                        } else {
                            TextView load_tv = (TextView) findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
        lv_my_collect.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                delBean = adapter.getLists().get(i);
                isDeleteDialog();
                return true;
            }
        });
    }

    /**
     * 获取我的收藏
     */
    public void myCollectData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.COLLECTLIST;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "page" + page, "time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("page", "" + page);
            parmaMap.put("time", time);
            parmaMap.put("sign", md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {

        }

    }

    /**
     * 删除我的收藏某一条数据
     */
    public void delMessageData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.UN_COLLECT;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String goods_id = delBean.goods_id;
            String[] sort = {"user_id" + user_id, "goods_id" + goods_id, "time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("goods_id",""+goods_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        } catch (Exception e) {

        }
    }

    /**
     * 删除我的收藏全部数据
     */
    public void delAllMessageData() {
        try {
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.CLEAR;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "type"+1,"time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("type", "1");
            parmaMap.put("time", time);
            parmaMap.put("sign", md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        } catch (Exception e) {
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case R.id.public_img_righe:
                delAllMessageData();
                break;
            default:
                break;
        }
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        myCollectData();
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null != paging.getString("page") && "1".equals(paging.getString("page"))) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                                JSONArray goods = json.getJSONArray("goods");
                                lists = Logic.getListToBean(goods, new MyCollectBean());
                                adapter.setLists(lists);
                                adapter.notifyDataSetChanged();

                            } else if (null != paging.getString("page") && !"1".equals(paging.getString("page"))) {
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray goods = (JSONArray) json.get("goods");
                                if (null != goods && goods.length() > 0) {
                                    List<MyCollectBean> listBean = Logic.getListToBean(goods, new MyCollectBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists.add(listBean.get(i));
                                    }
                                    adapter.setLists(lists);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }
                        } else if (state == 1) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            adapter.getLists().remove(delBean);
                            adapter.notifyDataSetChanged();
                        } else if (state == 1) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
            }
            if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            //清空全部数据
                            adapter.getLists().clear();
                            adapter.notifyDataSetChanged();
                        } else if (state == 1) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(MyCollectActivity.this, getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }

        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <= 1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }

    /**
     * 弹出删除消息
     */
    public void isDeleteDialog() {
        final PublicDialog dialog = new PublicDialog(this);
        dialog.setTitle(getResources().getString(R.string.xtts));// 设置title
        dialog.setContent(getResources().getString(R.string.scsc));// 设置内容
        dialog.setLeftButton(getResources().getString(R.string.qx));// 设置按钮
        dialog.setRightButton(getResources().getString(R.string.confirm));
        dialog.setLeftButtonVisible(true); // true显示 false隐藏
        dialog.setRightButtonVisible(true);// true显示 false隐藏
        dialog.setRightButtonClick(new PublicDialog.OnClickListener() {

            @Override
            public void onClick(View v) {
                //调用删除消息接口
                delMessageData();
            }
        });
        dialog.setLeftButtonClick(new PublicDialog.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismissDialog();
            }
        });
        dialog.showDialog();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(resultCode){
            case 0:
                if (null !=data) {
                    //说明用户在详情页面已取消收藏，需要重新调用列表接口
                    loadingDalog.show();
                    lists.clear();
                    adapter.notifyDataSetChanged();
                    myCollectData();
                }
                break;
        }
    }
}